local cjson = require "cjson"
result = {}
local buffer={}
local hostname = "www.baidu.com"
local mem = require "Memcached"
memcache = mem.Connect("127.0.0.1",11211)
if not memcache then
        ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
        ngx.say("service unavailabe")
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
end
local result = memcache:get(hostname)
if not result then
	require "luasql.mysql"
	env = luasql.mysql()
	if not env then
        ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
        ngx.say("service unavailabe")
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
    end
	result = "["
	con = env:connect("test","kangness","redhat","localhost",3306)			--建立链接
	if not con then
        ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
        ngx.say("service unavailabe")
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
    end
	local  cur = con:execute(string.format([[
			select hostname,ip from host where
			hostname = '%s']],hostname))			--从mysql中获取数据
	if not cur then
        ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
        ngx.say("service unavailabe")
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
    end
	row = cur:fetch ({},"a")			--下移游标
	if not row then
        ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
        ngx.say("service unavailabe")
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
    end
	while row do			--将mysql中的多条数据，整合成为一条json 方便保存到memcache中
		if result == '[' then
			result = result..row.ip
		else							---拼接json
		result = result..','..row.ip
		end
		row = cur:fetch(row,"a")
		
	end	
	result = result..']'
	cur:close()
	con:close()
	env:close()
	memcache:set(hostname,result)				--将数据回写到memcache中，加快下次访问
end

result = cjson.decode(result)					---将数据进行解码，获得表
if not result then
        ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
        ngx.say("service unavailabe")
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
end
if table.getn(result) ~= 1 then					---若不是仅仅一条ip地址信息的时候
	local i=1
	local number = 0
	local total = 0
	while (result[i]) do
		total = total + result[i].we				---计算加权的总和
		i = i+1
	end
	i = 1	
	math.randomseed(os.time())
	buffer = math.random(total)
	while result[i] do
		
		if result[i].we >= 1 then
			number = number +result[i].we
		else
			number = number +1
		end
		if buffer < number  then
			buffer = result[i].ip
			break
		else
			i = i+ 1
				
		end
	end
else					----若仅仅有一条ip信息的时候
	buffer = result[1].ip
end
result = buffer
print(result)


